<template>
  <div class="app-container">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="80px"
      label-position="top"
    >
      <el-card class="card_parent">
        <el-row :gutter="20" class="mb10">
          <el-col :span="8">
            <el-card class="card_operation">
              <div slot="header" class="clearfix">
                <el-row justify="center" type="flex">
                  <span>商品录入</span>
                </el-row>
              </div>
              <el-form
                :model="queryParams"
                ref="queryForm"
                size="small"
                :inline="true"
                v-show="showSearch"
                label-width="158px"
              >
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="商品编码" prop="id">
                      <el-input
                        v-model="queryParams.id"
                        placeholder="请输入产品名称"
                        clearable
                        @keyup.enter.native="handleQuery"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="数量" prop="quantity">
                      <el-input
                        v-model.number="queryParams.quantity"
                        placeholder="请输入数量"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-row type="flex" justify="center">
                      <el-button
                        type="primary"
                        icon="el-icon-search"
                        size="mini"
                        @click="handleQuery"
                        >搜索</el-button
                      >
                      <el-button
                        type="warning"
                        icon="el-icon-plus"
                        size="mini"
                        @click="handleAdd"
                        >录入</el-button
                      >
                      <el-button
                        icon="el-icon-refresh"
                        size="mini"
                        @click="resetQuery"
                        >重置</el-button
                      >
                    </el-row>
                  </el-col>
                </el-row>
              </el-form>
            </el-card>
          </el-col>
          <el-col :span="10">
            <el-card class="card_operation">
              <div slot="header" class="clearfix">
                <el-row justify="center" type="flex">
                  <span>优惠选择</span>
                </el-row>
              </div>
              <el-row type="flex" justify="center">
                <el-col :span="20">
                  <el-form-item prop="discount">
                    <el-radio-group
                      v-model="form.discount"
                      @change="calculateTotal"
                    >
                      <el-row>
                        <el-col :span="12" class="mb5"
                          ><el-radio label="0" border
                            >商品八折</el-radio
                          ></el-col
                        >
                        <el-col :span="12" class="mb5"
                          ><el-radio label="1" border
                            >满200-50</el-radio
                          ></el-col
                        >
                        <el-col :span="12" class="mb5">
                          <el-radio label="2" border>商品九折</el-radio></el-col
                        >
                        <el-col :span="12" class="mb5">
                          <el-radio label="3" border
                            >50RMB优惠卷</el-radio
                          ></el-col
                        >
                        <el-col :span="12" class="mb5">
                          <el-radio label="4" border
                            >20RMB优惠卷</el-radio
                          ></el-col
                        >
                        <el-col :span="12" class="mb5">
                          <el-radio label="9" border>无优惠</el-radio></el-col
                        >
                      </el-row>
                    </el-radio-group>
                  </el-form-item></el-col
                >
              </el-row>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="card_operation"
              ><div slot="header" class="clearfix">
                <el-row justify="center" type="flex">
                  <span>操作</span>
                </el-row>
              </div>
              <el-row
                type="flex"
                justify="center"
                align="middle"
                style="margin-top: 10px; margin-bottom: 20px"
              >
                <el-button type="primary" plain @click="submitForm('0')"
                  >挂单</el-button
                >
                <el-button plain @click="reset">重置</el-button>
              </el-row>
              <el-row type="flex" justify="center" align="middle">
                <el-button plain type="warning" @click="submitForm('1')"
                  >结算</el-button
                >
              </el-row>
            </el-card>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDeleteSaleDetail"
              >删除</el-button
            >
          </el-col>
        </el-row>
        <el-table
          :data="saleDetailList"
          height="350px"
          :row-class-name="rowSaleDetailIndex"
          @selection-change="handleSaleDetailSelectionChange"
          ref="saleDetail"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" />
          <el-table-column label="编号" prop="id"> </el-table-column>
          <el-table-column label="商品" prop="skuName">
            <template slot-scope="scope">
              <image-preview :src="scope.row.imgUrl" :width="50" :height="50" />
              {{ scope.row.skuName }}
            </template>
          </el-table-column>
          <el-table-column label="颜色" prop="color">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.sku_color"
                :value="scope.row.color"
              />
            </template>
          </el-table-column>
          <el-table-column label="尺码" prop="size">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sku_size" :value="scope.row.size" />
            </template>
          </el-table-column>
          <el-table-column label="价格" prop="skuPrice"> </el-table-column>
          <el-table-column label="数量" prop="quantity"> </el-table-column>
          <el-table-column label="库存" prop="skuStock"> </el-table-column>
          <el-table-column label="小计" prop="detailPrice"> </el-table-column>
        </el-table>
        <div class="laskettu-sarake">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="合计" prop="amount">
                {{ form.amount }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="数量" prop="quantity">
                {{ form.quantity }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="应收" prop="receivable">
                {{ form.receivable }}
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </el-form>

    <remark
      ref="remarkDialog"
      :visible.sync="remarkOpen"
      :title="remarkTitle"
      @confirm="handleConfirm"
    ></remark>
  </div>
</template>

<script>
import { addInfo } from "@/api/sale/info";
import { getSkuInfo } from "@/api/sale/skuInfo";
import remark from "./remark.vue";

export default {
  name: "Cashier",
  dicts: ["sale_discount", "order_status", "sku_color", "sku_size"],
  components: { remark },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSaleDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      infoList: [],
      // 订单详细表格数据
      saleDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        id: null,
        quantity: null,
        shelfStatus: "正常",
      },
      // 表单参数
      form: {
        discount: "9",
        quantity: 0,
        amount: 0,
        receivable: 0,
      },
      // 表单校验
      rules: {
        quantity: [
          { required: true, message: "商品数量不能为空", trigger: "blur" },
        ],
        discount: [
          { required: true, message: "折扣不能为空", trigger: "change" },
        ],
        amount: [{ required: true, message: "合计不能为空", trigger: "blur" }],
        receivable: [
          { required: true, message: "应收不能为空", trigger: "blur" },
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" },
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" },
        ],
      },
      readFlag: false,
      remarkOpen: false,
      remarkTitle: "1111",
    };
  },
  created() {},
  methods: {
    calculateTotal() {
      this.form.quantity = this.saleDetailList.reduce(
        (total, item) => total + parseInt(item.quantity),
        0
      );
      this.form.amount = this.saleDetailList.reduce(
        (total, item) => (total * 1 + item.detailPrice * 1).toFixed(2),
        0
      );
      if (this.form.amount > 0) {
        // 核算优惠
        switch (this.form.discount) {
          case "0":
            this.form.receivable = (this.form.amount * 0.8).toFixed(2);
            break;
          case "1":
            this.form.receivable =
              this.form.amount >= 200
                ? (this.form.amount - 50).toFixed(2)
                : (this.form.amount - 0).toFixed(2);
            break;
          case "2":
            this.form.receivable = (this.form.amount * 0.9).toFixed(2);
            break;
          case "3":
            this.form.receivable =
              this.form.amount > 50
                ? (this.form.amount - 50).toFixed(2)
                : (0).toFixed(2);
            break;
          case "4":
            this.form.receivable =
              this.form.amount > 20
                ? (this.form.amount - 20).toFixed(2)
                : (0).toFixed(2);
            break;
          default:
            this.form.receivable = (this.form.amount - 0).toFixed(2);
        }
      } else {
        this.form.receivable = 0;
      }
    },
    getSku(id) {
      getSkuInfo(id).then((response) => {
        if (response.data && response.data.shelfStatus === "正常") {
          this.$modal.alertSuccess("商品存在");
        } else {
          this.$modal.alert("商品不存在");
        }
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        quantity: null,
        discount: "9",
        amount: null,
        receivable: null,
        remark: null,
        status: null,
        createTime: null,
        updateTime: null,
      };
      this.saleDetailList = [];
      this.resetForm("form");
      this.calculateTotal();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (this.queryParams.id) {
        this.getSku(this.queryParams.id);
      } else {
        this.$modal.msgError("请输入商品编号");
      }
    },
    handleAdd() {
      if (this.queryParams.id && this.queryParams.quantity) {
        getSkuInfo(this.queryParams.id).then((response) => {
          const data = response.data;
          if (data && data.shelfStatus === "正常") {
            let find = this.saleDetailList.find(
              (e) => this.queryParams.id == e.id
            );
            if (find) {
              // 校验库存
              if (find.quantity + this.queryParams.quantity > data.skuStock) {
                this.$modal.alert("库存不足");
                return;
              }
              find.quantity += this.queryParams.quantity;
              find.detailPrice = (find.quantity * find.skuPrice).toFixed(2);
            } else {
              // 校验库存
              if (this.queryParams.quantity > data.skuStock) {
                this.$modal.alert("库存不足");
                return;
              }
              data.quantity = this.queryParams.quantity;
              data.detailPrice = (data.quantity * data.skuPrice).toFixed(2);
              data.skuId = data.id;
              this.saleDetailList.push(data);
            }
            this.calculateTotal();
            this.resetQuery();
          } else {
            this.$modal.alert("商品不存在");
          }
        });
      } else {
        this.$modal.msgError("请输入商品编号或数量");
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
    },
    /** 提交按钮 */
    submitForm(type) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.calculateTotal();
          if (this.form.amount <= 0) {
            this.$modal.msgError(`合计必须大于0`);
            return;
          }
          this.form.status = "1";
          this.form.saleDetailList = this.saleDetailList;
          this.form.type = type;
          this.remarkOpen = true;
          this.remarkTitle = type == "0" ? "挂单" : "结算";
        }
      });
    },
    handleConfirm(remark) {
      this.form.remark = remark;
      const type = this.form.type;
      addInfo(this.form).then((res) => {
        this.$modal.msgSuccess("操作成功");
        this.reset();
        if (type == "1") {
          this.$tab.openPage(
            "支付[" + res.data + "]订单",
            "/sell/pay/index/" + res.data,
            {}
          );
        }
      });
    },
    /** 订单详细序号 */
    rowSaleDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 订单详细删除按钮操作 */
    handleDeleteSaleDetail() {
      if (this.checkedSaleDetail.length == 0) {
        this.$modal.msgError("请先选择要删除的订单详细数据");
      } else {
        const saleDetailList = this.saleDetailList;
        const checkedSaleDetail = this.checkedSaleDetail;
        this.saleDetailList = saleDetailList.filter(function (item) {
          return checkedSaleDetail.indexOf(item.index) == -1;
        });
        this.calculateTotal();
      }
    },
    /** 复选框选中数据 */
    handleSaleDetailSelectionChange(selection) {
      this.checkedSaleDetail = selection.map((item) => item.index);
    },
  },
};
</script>

<style scoped>
.card_parent {
  margin: 10px 20px;
  min-height: 770px;
}
.card_operation {
  height: 240px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.el-radio::v-deep .el-radio__label {
  font-size: 20px; /* 修改为所需的字体大小 */
}
.laskettu-sarake {
  background-color: #e6e6fa;
  height: 90px;
}
</style>
